const { Service, Schema } = require('koishi')
const axios = require('axios')
const z = require('zod')

/**
 * @description 剑网三API服务类，负责请求剑网三相关数据
 */
class Jx3ApiService extends Service {
  /**
   * @param {object} ctx - Koishi上下文
   * @param {object} config - 插件配置
   */
  constructor(ctx, config) {
    super(ctx, 'jx3Api')
    this.config = config
    this.httpClient = axios.create({
      baseURL: config.baseUrl,
      headers: {
        'Authorization': `Bearer ${config.apiKey}`,
        'Content-Type': 'application/json'
      },
      timeout: 10000
    })

    // 设置本地缓存
    this.cache = {}
    this.cacheExpiry = {}
  }

  /**
   * @description 获取角色信息
   * @param {string} roleName - 角色名称
   * @param {string} server - 服务器名称
   * @returns {Promise<object>} 角色信息
   */
  async getRoleInfo(roleName, server) {
    const cacheKey = `role_${server}_${roleName}`
    if (this._checkCache(cacheKey)) {
      return this.cache[cacheKey]
    }

    try {
      const response = await this.httpClient.get('/role/info', {
        params: { name: roleName, server }
      })
      this._setCache(cacheKey, response.data)
      return response.data
    } catch (error) {
      this.ctx.logger.error('获取角色信息失败:', error)
      throw new Error('获取角色信息失败，请稍后重试')
    }
  }

  /**
   * @description 获取角色装备信息
   * @param {string} roleName - 角色名称
   * @param {string} server - 服务器名称
   * @returns {Promise<object>} 装备信息
   */
  async getRoleEquip(roleName, server) {
    const cacheKey = `equip_${server}_${roleName}`
    if (this._checkCache(cacheKey)) {
      return this.cache[cacheKey]
    }

    try {
      const response = await this.httpClient.get('/role/equip', {
        params: { name: roleName, server }
      })
      this._setCache(cacheKey, response.data)
      return response.data
    } catch (error) {
      this.ctx.logger.error('获取角色装备失败:', error)
      throw new Error('获取角色装备失败，请稍后重试')
    }
  }

  /**
   * @description 获取副本信息
   * @param {string} dungeonName - 副本名称
   * @returns {Promise<object>} 副本信息
   */
  async getDungeonInfo(dungeonName) {
    const cacheKey = `dungeon_${dungeonName}`
    if (this._checkCache(cacheKey)) {
      return this.cache[cacheKey]
    }

    try {
      const response = await this.httpClient.get('/dungeon/info', {
        params: { name: dungeonName }
      })
      this._setCache(cacheKey, response.data)
      return response.data
    } catch (error) {
      this.ctx.logger.error('获取副本信息失败:', error)
      throw new Error('获取副本信息失败，请稍后重试')
    }
  }

  /**
   * @description 获取日常活动信息
   * @returns {Promise<object>} 日常活动信息
   */
  async getDailyActivities() {
    const cacheKey = 'daily_activities'
    if (this._checkCache(cacheKey)) {
      return this.cache[cacheKey]
    }

    try {
      const response = await this.httpClient.get('/activities/daily')
      this._setCache(cacheKey, response.data)
      return response.data
    } catch (error) {
      this.ctx.logger.error('获取日常活动失败:', error)
      throw new Error('获取日常活动失败，请稍后重试')
    }
  }

  /**
   * @description 缓存检查
   * @private
   * @param {string} key - 缓存键
   * @returns {boolean} 是否命中缓存
   */
  _checkCache(key) {
    return this.cache[key] && this.cacheExpiry[key] > Date.now()
  }

  /**
   * @description 设置缓存
   * @private
   * @param {string} key - 缓存键
   * @param {any} data - 缓存数据
   */
  _setCache(key, data) {
    this.cache[key] = data
    this.cacheExpiry[key] = Date.now() + this.config.cacheTime
  }
}

// 配置模式定义
const configSchema = Schema.object({
  apiKey: Schema.string().required(),
  baseUrl: Schema.string().default('https://api.jx3.com/v1'),
  cacheTime: Schema.number().default(3600000)
})

// 插件主方法
module.exports.name = 'jx3-api'
module.exports.inject = ['database']

module.exports.Config = configSchema

module.exports.apply = (ctx, config) => {
  // 注册服务
  ctx.plugin(Jx3ApiService, config)
  
  ctx.on('ready', () => {
    ctx.logger.info('剑网三API服务已启动')
  })
} 